package com.ztorn.fiscale.service.impl;

import java.util.List;
import java.util.Date;
import java.util.ArrayList;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;

import com.ztorn.common.core.utils.DateUtils;
import com.ztorn.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ztorn.fiscale.mapper.FiscaleCustomsDeclarationMapper;
import com.ztorn.fiscale.mapper.FiscaleOrderMapper;
import com.ztorn.fiscale.domain.FiscaleCustomsDeclaration;
import com.ztorn.fiscale.domain.FiscaleCustomsDeclarationOrder;
import com.ztorn.fiscale.domain.FiscaleCustomsDeclarationItem;
import com.ztorn.fiscale.domain.FiscaleOrder;
import com.ztorn.fiscale.domain.FiscaleOrderItem;
import com.ztorn.fiscale.service.IFiscaleCustomsDeclarationService;

/**
 * 报关单管理Service业务层处理
 *
 * @author ztorn
 * @date 2025-01-19
 */
@Service
public class FiscaleCustomsDeclarationServiceImpl implements IFiscaleCustomsDeclarationService
{
    @Autowired
    private FiscaleCustomsDeclarationMapper fiscaleCustomsDeclarationMapper;

    @Autowired
    private FiscaleOrderMapper fiscaleOrderMapper;

    /**
     * 查询报关单管理
     *
     * @param declarationId 报关单管理主键
     * @return 报关单管理
     */
    @Override
    public FiscaleCustomsDeclaration selectFiscaleCustomsDeclarationByDeclarationId(Long declarationId)
    {
        return fiscaleCustomsDeclarationMapper.selectFiscaleCustomsDeclarationByDeclarationId(declarationId);
    }

    /**
     * 查询报关单管理列表
     *
     * @param fiscaleCustomsDeclaration 报关单管理
     * @return 报关单管理
     */
    @Override
    public List<FiscaleCustomsDeclaration> selectFiscaleCustomsDeclarationList(FiscaleCustomsDeclaration fiscaleCustomsDeclaration)
    {
        return fiscaleCustomsDeclarationMapper.selectFiscaleCustomsDeclarationList(fiscaleCustomsDeclaration);
    }

    /**
     * 新增报关单管理
     *
     * @param fiscaleCustomsDeclaration 报关单管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertFiscaleCustomsDeclaration(FiscaleCustomsDeclaration fiscaleCustomsDeclaration)
    {
        fiscaleCustomsDeclaration.setCreateTime(DateUtils.getNowDate());
        fiscaleCustomsDeclaration.setCreateBy(SecurityUtils.getUsername());
        if (fiscaleCustomsDeclaration.getDeclarationNo() == null || fiscaleCustomsDeclaration.getDeclarationNo().isEmpty()) {
            fiscaleCustomsDeclaration.setDeclarationNo(generateDeclarationNo());
        }
        if (fiscaleCustomsDeclaration.getCustomsStatus() == null || fiscaleCustomsDeclaration.getCustomsStatus().isEmpty()) {
            fiscaleCustomsDeclaration.setCustomsStatus("draft");
        }
        // 设置删除标志
        fiscaleCustomsDeclaration.setDelFlag("0");
        int rows = fiscaleCustomsDeclarationMapper.insertFiscaleCustomsDeclaration(fiscaleCustomsDeclaration);
        insertFiscaleCustomsDeclarationOrder(fiscaleCustomsDeclaration);
        insertFiscaleCustomsDeclarationItem(fiscaleCustomsDeclaration);
        return rows;
    }

    /**
     * 修改报关单管理
     *
     * @param fiscaleCustomsDeclaration 报关单管理
     * @return 结果
     */
    @Transactional
    @Override
    public int updateFiscaleCustomsDeclaration(FiscaleCustomsDeclaration fiscaleCustomsDeclaration)
    {
        fiscaleCustomsDeclaration.setUpdateTime(DateUtils.getNowDate());
        fiscaleCustomsDeclaration.setUpdateBy(SecurityUtils.getUsername());
        fiscaleCustomsDeclarationMapper.deleteFiscaleCustomsDeclarationOrderByDeclarationId(fiscaleCustomsDeclaration.getDeclarationId());
        insertFiscaleCustomsDeclarationOrder(fiscaleCustomsDeclaration);
        fiscaleCustomsDeclarationMapper.deleteFiscaleCustomsDeclarationItemByDeclarationId(fiscaleCustomsDeclaration.getDeclarationId());
        insertFiscaleCustomsDeclarationItem(fiscaleCustomsDeclaration);
        return fiscaleCustomsDeclarationMapper.updateFiscaleCustomsDeclaration(fiscaleCustomsDeclaration);
    }

    /**
     * 批量删除报关单管理
     *
     * @param declarationIds 需要删除的报关单管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteFiscaleCustomsDeclarationByDeclarationIds(Long[] declarationIds)
    {
        // 检查报关单状态，只有草稿状态的才能删除
        for (Long declarationId : declarationIds) {
            FiscaleCustomsDeclaration declaration = selectFiscaleCustomsDeclarationByDeclarationId(declarationId);
            if (declaration != null && !"draft".equals(declaration.getCustomsStatus())) {
                throw new RuntimeException("只有草稿状态的报关单才能删除，报关单号:" + declaration.getDeclarationNo() + " 状态:" + declaration.getCustomsStatus());
            }
        }
        
        fiscaleCustomsDeclarationMapper.deleteFiscaleCustomsDeclarationOrderByDeclarationIds(declarationIds);
        fiscaleCustomsDeclarationMapper.deleteFiscaleCustomsDeclarationItemByDeclarationIds(declarationIds);
        return fiscaleCustomsDeclarationMapper.deleteFiscaleCustomsDeclarationByDeclarationIds(declarationIds);
    }

    /**
     * 删除报关单管理信息
     *
     * @param declarationId 报关单管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteFiscaleCustomsDeclarationByDeclarationId(Long declarationId)
    {
        // 检查报关单状态，只有草稿状态的才能删除
        FiscaleCustomsDeclaration declaration = selectFiscaleCustomsDeclarationByDeclarationId(declarationId);
        if (declaration != null && !"draft".equals(declaration.getCustomsStatus())) {
            throw new RuntimeException("只有草稿状态的报关单才能删除，报关单号:" + declaration.getDeclarationNo() + " 状态:" + declaration.getCustomsStatus());
        }
        
        fiscaleCustomsDeclarationMapper.deleteFiscaleCustomsDeclarationOrderByDeclarationId(declarationId);
        fiscaleCustomsDeclarationMapper.deleteFiscaleCustomsDeclarationItemByDeclarationId(declarationId);
        return fiscaleCustomsDeclarationMapper.deleteFiscaleCustomsDeclarationByDeclarationId(declarationId);
    }

    /**
     * 根据报关单号查询报关单
     *
     * @param declarationNo 报关单号
     * @return 报关单信息
     */
    @Override
    public FiscaleCustomsDeclaration selectFiscaleCustomsDeclarationByDeclarationNo(String declarationNo)
    {
        return fiscaleCustomsDeclarationMapper.selectFiscaleCustomsDeclarationByDeclarationNo(declarationNo);
    }

    /**
     * 生成报关单号
     *
     * @return 报关单号
     */
    @Override
    public String generateDeclarationNo()
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        String prefix = "BGD" + dateStr;

        // 查询今天已经生成的报关单号数量 - 修复查询逻辑
        FiscaleCustomsDeclaration query = new FiscaleCustomsDeclaration();
        List<FiscaleCustomsDeclaration> list = fiscaleCustomsDeclarationMapper.selectFiscaleCustomsDeclarationList(query);
        
        // 过滤出今天的报关单号
        long todayCount = list.stream()
            .filter(declaration -> declaration.getDeclarationNo() != null && declaration.getDeclarationNo().startsWith(prefix))
            .count();

        int sequence = (int) todayCount + 1;
        return prefix + String.format("%03d", sequence);
    }

    /**
     * 从订单创建报关单
     *
     * @param fiscaleCustomsDeclaration 报关单信息
     * @param orderIds 订单ID数组
     * @return 结果
     */
    @Transactional
    @Override
    public int createDeclarationFromOrders(FiscaleCustomsDeclaration fiscaleCustomsDeclaration, Long[] orderIds)
    {
        // 查询订单信息
        FiscaleOrder orderQuery = new FiscaleOrder();
        orderQuery.setOrderIds(orderIds);
        List<FiscaleOrder> orders = fiscaleOrderMapper.selectFiscaleOrderList(orderQuery);

        if (orders == null || orders.isEmpty()) {
            throw new RuntimeException("未找到指定的订单信息");
        }

        // 检查订单是否已经报关
        for (FiscaleOrder order : orders) {
            if ("declared".equals(order.getCustomsStatus()) || "declaring".equals(order.getCustomsStatus())) {
                throw new RuntimeException("订单 " + order.getOrderNo() + " 已经报关或正在报关中，不能重复报关");
            }
        }

        // 计算报关单汇总信息
        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal totalWeight = BigDecimal.ZERO;
        Long totalPackages = 0L;

        List<FiscaleCustomsDeclarationOrder> declarationOrderList = new ArrayList<>();
        List<FiscaleCustomsDeclarationItem> declarationItemList = new ArrayList<>();

        for (FiscaleOrder order : orders) {
            totalAmount = totalAmount.add(order.getTotalAmount() != null ? order.getTotalAmount() : BigDecimal.ZERO);
            totalWeight = totalWeight.add(order.getTotalWeight() != null ? order.getTotalWeight() : BigDecimal.ZERO);
            totalPackages += order.getTotalQuantity() != null ? order.getTotalQuantity() : 0L;

            // 创建报关单订单关联
            FiscaleCustomsDeclarationOrder declarationOrder = new FiscaleCustomsDeclarationOrder();
            declarationOrder.setOrderId(order.getOrderId());
            declarationOrder.setOrderNo(order.getOrderNo());
            declarationOrder.setOrderAmount(order.getTotalAmount());
            declarationOrder.setOrderWeight(order.getTotalWeight());
            declarationOrder.setOrderPackages(order.getTotalQuantity());
            declarationOrder.setCreateTime(new Date());
            declarationOrderList.add(declarationOrder);

            // 创建报关单商品明细
            if (order.getOrderItems() != null) {
                for (FiscaleOrderItem orderItem : order.getOrderItems()) {
                    FiscaleCustomsDeclarationItem declarationItem = new FiscaleCustomsDeclarationItem();
                    declarationItem.setOrderId(order.getOrderId());
                    declarationItem.setOrderItemId(orderItem.getItemId());
                    declarationItem.setProductName(orderItem.getProductName());
                    declarationItem.setProductNameEn(orderItem.getProductNameEn());
                    declarationItem.setHsCode(orderItem.getHsCode());
                    declarationItem.setSpecification(orderItem.getSpecification());
                    declarationItem.setQuantity(orderItem.getQuantity().longValue());
                    declarationItem.setUnit(orderItem.getUnit());
                    declarationItem.setUnitPrice(orderItem.getUnitPrice());
                    declarationItem.setTotalPrice(orderItem.getTotalPrice());
                    declarationItem.setWeight(orderItem.getWeight());
                    declarationItem.setCountryOfOrigin(orderItem.getCountryOfOrigin());
                    declarationItem.setBrand(orderItem.getBrand());
                    declarationItem.setModel(orderItem.getModel());
                    declarationItem.setCreateTime(new Date());
                    declarationItemList.add(declarationItem);
                }
            }
        }

        // 设置报关单汇总信息
        fiscaleCustomsDeclaration.setTotalAmount(totalAmount);
        fiscaleCustomsDeclaration.setTotalWeight(totalWeight);
        fiscaleCustomsDeclaration.setTotalPackages(totalPackages);
        fiscaleCustomsDeclaration.setDeclarationOrderList(declarationOrderList);
        fiscaleCustomsDeclaration.setDeclarationItemList(declarationItemList);

        // 插入报关单
        int result = insertFiscaleCustomsDeclaration(fiscaleCustomsDeclaration);
        
        // 更新订单状态为"已报关"
        if (result > 0) {
            fiscaleOrderMapper.batchUpdateCustomsStatus(orderIds, "declared", SecurityUtils.getUsername());
        }
        
        return result;
    }

    /**
     * 提交报关单
     *
     * @param declarationId 报关单ID
     * @return 结果
     */
    @Override
    public int submitCustomsDeclaration(Long declarationId)
    {
        return fiscaleCustomsDeclarationMapper.submitCustomsDeclaration(declarationId, new Date(), SecurityUtils.getUsername());
    }

    /**
     * 审批报关单
     *
     * @param declarationId 报关单ID
     * @param customsStatus 报关状态
     * @param customsOfficer 报关员
     * @return 结果
     */
    @Override
    public int approveCustomsDeclaration(Long declarationId, String customsStatus, String customsOfficer)
    {
        return fiscaleCustomsDeclarationMapper.approveCustomsDeclaration(declarationId, customsStatus, customsOfficer, SecurityUtils.getUsername());
    }

    /**
     * 批量更新报关单状态
     *
     * @param declarationIds 报关单ID数组
     * @param customsStatus 报关状态
     * @return 结果
     */
    @Override
    public int batchUpdateCustomsStatus(Long[] declarationIds, String customsStatus)
    {
        return fiscaleCustomsDeclarationMapper.batchUpdateCustomsStatus(declarationIds, customsStatus, SecurityUtils.getUsername());
    }

    /**
     * 新增报关单订单关联信息
     *
     * @param fiscaleCustomsDeclaration 报关单对象
     */
    public void insertFiscaleCustomsDeclarationOrder(FiscaleCustomsDeclaration fiscaleCustomsDeclaration)
    {
        List<FiscaleCustomsDeclarationOrder> declarationOrderList = fiscaleCustomsDeclaration.getDeclarationOrderList();
        Long declarationId = fiscaleCustomsDeclaration.getDeclarationId();
        if (declarationOrderList != null && !declarationOrderList.isEmpty())
        {
            for (FiscaleCustomsDeclarationOrder declarationOrder : declarationOrderList)
            {
                declarationOrder.setDeclarationId(declarationId);
            }
            fiscaleCustomsDeclarationMapper.batchFiscaleCustomsDeclarationOrder(declarationOrderList);
        }
    }

    /**
     * 新增报关单商品明细信息
     *
     * @param fiscaleCustomsDeclaration 报关单对象
     */
    public void insertFiscaleCustomsDeclarationItem(FiscaleCustomsDeclaration fiscaleCustomsDeclaration)
    {
        List<FiscaleCustomsDeclarationItem> declarationItemList = fiscaleCustomsDeclaration.getDeclarationItemList();
        Long declarationId = fiscaleCustomsDeclaration.getDeclarationId();
        if (declarationItemList != null && !declarationItemList.isEmpty())
        {
            for (FiscaleCustomsDeclarationItem declarationItem : declarationItemList)
            {
                declarationItem.setDeclarationId(declarationId);
            }
            fiscaleCustomsDeclarationMapper.batchFiscaleCustomsDeclarationItem(declarationItemList);
        }
    }
}
